<?php


namespace app\index\model;


use app\index\controller\OrderController;
use think\Exception;
use think\Model;

class Purchase extends Model
{

    public static $type_list=[['id'=>1,'label'=>'新品采购'],['id'=>2,'label'=>'找货单']];
    /**
     * 执行添加购物单
     * create by yhb on 2021/3/11 12:59
     * @param $data
     * @return array
     * @throws \think\exception\PDOException
     */
    public function addPurchase($insert_purchase,$insert_purchase_detail,$update_product)
    {
        $productClass=new Product();
        $purchaseClass = new self();
        $purchaseDetailClass=new PurchaseDetail();


        $purchaseClass->startTrans();
        try {
            $result = $purchaseClass->save($insert_purchase);
            if($result===0){
                return ['status'=>false,'result'=>'添加失败'];
            }
            foreach($insert_purchase_detail as $key=>$value){
                $insert_purchase_detail[$key]['pur_id'] = $purchaseClass->id;
            }

            $result=$purchaseDetailClass->saveAll($insert_purchase_detail);
            if($result===0){
                return ['status'=>false,'result'=>'保存详情失败'];
            }

            $result= $productClass->isUpdate(true)->saveAll($update_product);
            if($result===0){
                return ['status'=>false,'result'=>'保存商品失败'];
            }
            $purchaseClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (\Exception $e) {
            $purchaseClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'.$e->getMessage()];
        }
    }

    /**
     * 添加采购新品和新的供应商
     * create by yhb on 2021/3/13 9:21
     * @param $purchase_data
     * @param $vendor_data
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function addNewPurchase($purchase_data,$vendor_data)
    {
        $purchaseClass = new self();
        $purchaseDetailClass = new PurchaseDetail();
        $vendorClass = new Vendor();

        $purchaseClass->startTrans();
        try {
            if(isset($vendor_data['company'])) {
                $vendorObj = $vendorClass
                    ->where('company', $vendor_data['company'])
                    ->field('id')
                    ->find();
                if (!empty($vendorObj)) {
                    $vendorId = $vendorObj->toArray();
                    $vendor_data['id']=$vendorId['id'];
                }
            }
            $result = $vendorClass->isUpdate(isset($vendor_data['id']))->save($vendor_data);
            if($result===false){
                return ['status'=>false,'result'=>'保存供应商失败'];
            }
            $vendor_data['id']=$vendorClass->id;
            $purchase_data['vendor_id']=$vendor_data['id'];


            $result=$purchaseClass->save(['type'=>1, 'purchase_id'=>'PUR'.$purchaseClass::generatePurchaserId(),'create_user'=>$purchase_data['create_user']]);
            if($result===false){
                return ['status'=>false,'result'=>'添加采购失败'];
            }
            $purchase_data['pur_id']=$purchaseClass->id;
            $result=$purchaseDetailClass->isUpdate(false)->save($purchase_data);
            if($result===false){
                return ['status'=>false,'result'=>'添加采购详情失败'];
            }

            $purchaseClass->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (\Exception $e) {
            $purchaseClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'.$e->getMessage()];
        }
    }

    /**
     * 获取采购单号
     * create by yhb on 2021/3/11 14:21
     * @param int $num
     * @return string
     * @throws Exception
     */
    public static function generatePurchaserId($num=0)
    {
        $count=Purchase::where('create_time','>=',date('Y-m-d').' 00:00:00')->count();
        if($count===null){
            $count=0;
        }
        $id=date('ymd').'0000';
        $purchase_id=$count+$num+1;
        $max_id_len=strlen($purchase_id);

        $id_len=strlen($id);
        if($max_id_len>4){
            $max_id_len=4;
        }
        return substr($id,0,$id_len-$max_id_len).($purchase_id);
    }

    /**
     * 批量添加新品采购
     * create by yhb on 2021/3/31 18:41
     * @param $data
     * @return array
     * @throws Exception
     * @throws \think\exception\PDOException
     */
    public static function insertBatchPurchase($insert_purchase,$insert_purchase_detail,$vendor)
    {
        $Purchase=new Purchase();
        $purchaseDetailClass = new PurchaseDetail();
        $vendorClass = new Vendor();

        $Purchase->startTrans();
        try {
            if(is_numeric($vendor)){
                $vendorId=$vendor;
            }else{
                $obj = $vendorClass->where('company',$vendor)->where('del_flag',0)->field('id')->find();
                if(!empty($obj)){
                    $vendorId = $obj['id'];
                }else{
                    $insert_vendor = ['company' => $vendor,];
                    $result = $vendorClass->save($insert_vendor);
                    if($result===false){
                        return ['status'=>false,'result'=>'添加供应商失败'];
                    }
                    $vendorId = $vendorClass->id;
                }
            }

            $result = $Purchase->save($insert_purchase);
            if($result===false){
                return ['status'=>false,'result'=>'添加采购失败'];
            }
            foreach ($insert_purchase_detail as $key=>$value){
                $insert_purchase_detail[$key]['vendor_id'] = $vendorId;
                $insert_purchase_detail[$key]['pur_id'] = $Purchase->id;
            }

            $result=$purchaseDetailClass->saveAll($insert_purchase_detail);
            if($result===false){
                return ['status'=>false,'result'=>'保存采购详情失败'];
            }

            $Purchase->commit();
            return ['status'=>true,'result'=>'添加成功'];
        }catch (\Exception $e) {
            $Purchase->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'.$e->getMessage()];
        }
    }


}